package com.shop.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.entity.dto.AdminCost.*;
import com.shop.entity.dto.AdminStyle.AdminStyleCostDto;
import com.shop.entity.dto.AdminWares.*;
import com.shop.entity.pojo.*;
import com.shop.admin.mapper.AdminUserMapper;
import com.shop.admin.mapper.CostMapper;
import com.shop.admin.mapper.StyleMapper;
import com.shop.admin.mapper.WaresMapper;
import com.shop.admin.service.CostService;
import com.shop.utils.common.enums.Code;
import com.shop.utils.common.enums.Message;
import com.shop.utils.common.result.PageResponseResult;
import com.shop.utils.common.result.Result;
import com.shop.utils.config.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class CostServiceImpl extends ServiceImpl<CostMapper, Cost> implements CostService {

    @Autowired
    private CostMapper costMapper;
    @Autowired
    private AdminUserMapper adminUserMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StyleMapper styleMapper;
    @Autowired
    private WaresMapper waresMapper;

    @Override
    public Result saveOneCost(AdminCostSaveDto dto) {

        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        if (adminUser==null||adminId==null) {
            Result.errorResult(Code.PARAM_INVALID);
        }
        String k=Message.WeChat_Key_Style+dto.getStyleId();
        redisTemplate.delete(k);
        List<Cost> costList = costMapper.selectList(Wrappers.<Cost>lambdaQuery()
                .eq(Cost::getWaresId, dto.getWaresId())
                .eq(Cost::getStyleId, dto.getStyleId())
                .eq(Cost::getCostMessage, dto.getCostMessage())
                .eq(Cost::getWaresPrice, dto.getCostPrice()));
        if (!CollectionUtils.isEmpty(costList)||costList.size()>Message.Check_Int_Null) {
            return Result.errorResult(Code.DATA_EXIST);
        }
        Cost cost=new Cost();
        cost= cost.builder()
                .waresId(dto.getWaresId())
                .styleId(dto.getStyleId())
                .costMessage(dto.getCostMessage())
                .waresPrice(dto.getCostPrice())
                .saveAdmin(adminUser.getName())
                .saveTime(String.valueOf(LocalDateTime.now())).build();
        boolean save = save(cost);
        if (!save) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        redisTemplate.delete(k);
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result<List<Cost>> getWaresCost(AdminWaresCostListDto dto) {

        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        dto.checkParam();
        Page<Cost> page=new Page<>(dto.getPage(),dto.getSize());
        Page<Cost> value = costMapper.getByWaresId(page, dto.getWaresId());
        Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) value.getTotal());
        result.setData(value.getRecords());
        return result;
    }


    @Override
    public Result updateCost(AdminCostUpdateDto dto) {
        if (dto==null) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectOne(Wrappers.<AdminUser>lambdaQuery().eq(AdminUser::getId, adminId));
        if (adminUser==null||adminId==null) {
            return Result.errorResult(Code.PARAM_INVALID);
        }
        Cost oldCost = getOne(Wrappers.<Cost>lambdaQuery().eq(Cost::getId, dto.getCostId()));
        if (oldCost==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        String k=Message.WeChat_Key_Style+oldCost.getStyleId();
        redisTemplate.delete(k);
        String costMessage=oldCost.getCostMessage();
        if (dto.getCostMessage()!=null) {
            List<Cost> message = costMapper.selectList(Wrappers.<Cost>lambdaQuery()
                    .eq(Cost::getCostMessage, dto.getCostMessage())
                    .eq(Cost::getStyleId,oldCost.getStyleId()));
            if (!CollectionUtils.isEmpty(message)||message.size()>Message.Check_Int_Null) {
                return Result.errorResult(Code.DATA_EXIST);
            }
            costMessage= dto.getCostMessage();
        }
        double waresPrice=oldCost.getWaresPrice();
        if (dto.getWaresPrice()!=Message.Check_Int_Null) {
            waresPrice=dto.getWaresPrice();
        }

        Cost cost=new Cost();
        cost=cost.builder()
                .costMessage(costMessage)
                .waresPrice(waresPrice)
                .saveAdmin(adminUser.getName())
                .saveAdmin(adminUser.getName()).build();
        boolean update = update(cost, Wrappers.<Cost>lambdaUpdate().eq(Cost::getId, dto.getCostId()));
        if (!update) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        redisTemplate.delete(k);
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result removeCost(AdminCostRemoveDto dto) {

        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        if (adminId==null||adminUser==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        Cost cost = costMapper.selectById(dto.getCostId());
        if (cost==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        String k=Message.WeChat_Key_Style+cost.getStyleId();
        redisTemplate.delete(k);
        Cost newCost=new Cost();
        newCost= newCost.builder()
                .removeMemo(dto.getRemoveMemo())
                .removeAdmin(adminUser.getName()).build();
        boolean update = update(newCost, Wrappers.<Cost>lambdaUpdate().eq(Cost::getId, dto.getCostId()));
        if (!update) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        int delCost = costMapper.deleteById(dto.getCostId());
        if (delCost==Message.Check_Int_False) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        redisTemplate.delete(k);
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result<Cost> updateGetCost(AdminCostUpdateForGetDto dto) {
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Cost cost = getOne(Wrappers.<Cost>lambdaQuery().eq(Cost::getId, dto.getCostId()));
        if (cost==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        return Result.okResult(cost);
    }

    @Override
    public Result getCostList(AdminCostListDto dto) {
        dto.checkParam();
        Page<Cost> page=new Page<>(dto.getPage(),dto.getSize());
        Page<Cost> value = costMapper.getAllByPage(page, dto);
        Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) value.getTotal());
        result.setData(value.getRecords());
        return result;
    }

    @Override
    public Result openCost(AdminCostOpenDto dto) {
        if ( dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        Cost byId = costMapper.getOne(dto.getCostId());
        if (adminId==null||adminUser==null||byId==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        if (byId.getIsDelete()==Message.Delete_True) {
            return Result.errorResult(Code.PARAM_INVALID);
        }
        String k=Message.WeChat_Key_Style+byId.getStyleId();
        redisTemplate.delete(k);
        Cost cost=new Cost();
        cost=cost.builder()
                .id(dto.getCostId())
                .removeAdmin(null)
                .removeMemo(null)
                .isDelete(Message.Put)
                .saveAdmin(adminUser.getName())
                .saveTime(String.valueOf(LocalDateTime.now()))
                .version(byId.getVersion()+Message.Version_Up).build();
        boolean update = costMapper.updateIsDelete(cost);
        if (!update) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        redisTemplate.delete(k);
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result getStyleCostByPage(AdminStyleCostDto dto) {
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        dto.checkParam();
        Page<Cost> page=new Page<>(dto.getPage(),dto.getSize());
        Page<Cost> value = costMapper.CostPageByStyleId(page, dto);
        Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) value.getTotal());
        result.setData(value.getRecords());
        return result;
    }

    @Override
    public Result pullCost(AdminCostPullDto dto) {
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        if (adminUser==null||adminId==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        Style style=new Style();
        Cost cost=new Cost();
        Cost checkCost = costMapper.selectById(dto.getCostId());
        if (checkCost==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        String k=Message.WeChat_Key_Style+checkCost.getStyleId();
        redisTemplate.delete(k);
        cost= cost.builder().state(Message.Pull).removeAdmin(adminUser.getName()).removeMemo(dto.getMemo()).build();
        style.setState(Message.Exception);
        int pullCost = costMapper.update(cost, Wrappers.<Cost>lambdaUpdate().eq(Cost::getId, dto.getCostId()));
        if (pullCost==Message.Check_Int_False) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        redisTemplate.delete(k);
        return Result.errorResult(Code.SUCCESS);
    }

    @Override
    public Result putCost(AdminCostPutDto dto) {
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        if (adminUser==null||adminId==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        Cost cost=new Cost();
        Cost checkCost = costMapper.selectById(dto.getCostId());
        if (checkCost==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        String k=Message.WeChat_Key_Style+checkCost.getStyleId();
        redisTemplate.delete(k);
        cost= cost.builder().state(Message.Put).saveAdmin(adminUser.getName()).saveTime(String.valueOf(LocalDateTime.now())).build();
        int pullCost = costMapper.update(cost, Wrappers.<Cost>lambdaUpdate().eq(Cost::getId, dto.getCostId()));
        if (pullCost==Message.Check_Int_False) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        redisTemplate.delete(k);
        return Result.errorResult(Code.SUCCESS);
    }

}
